w1w#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pymysql
import os
import sys

# 获取当前脚本所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 获取项目根目录
root_dir = os.path.dirname(current_dir)
# 将项目根目录添加到系统路径
sys.path.append(root_dir)

# 导入数据库配置
try:
    from app import DB_CONFIG
except ImportError:
    # 如果无法导入，使用默认配置
    DB_CONFIG = {
        'host': 'localhost',
        'user': 'root',
        'password': '',  # 请修改为您的数据库密码
        'db': 'huawei_ending',
        'charset': 'utf8mb4',
        'cursorclass': pymysql.cursors.DictCursor
    }

def init_database():
    """初始化数据库"""
    # 读取SQL文件
    with open(os.path.join(current_dir, 'create_tables.sql'), 'r', encoding='utf-8') as f:
        sql_script = f.read()
    
    # 分割SQL语句
    sql_commands = sql_script.split(';')
    
    # 连接数据库
    try:
        conn = pymysql.connect(
            host=DB_CONFIG['host'],
            user=DB_CONFIG['user'],
            password=DB_CONFIG['password'],
            charset=DB_CONFIG['charset']
        )
        
        with conn.cursor() as cursor:
            # 创建数据库（如果不存在）
            cursor.execute(f"CREATE DATABASE IF NOT EXISTS `{DB_CONFIG['db']}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
            # 使用数据库
            cursor.execute(f"USE `{DB_CONFIG['db']}`")
            
            # 执行每个SQL命令
            for command in sql_commands:
                command = command.strip()
                if command:
                    cursor.execute(command)
            
            conn.commit()
            print("数据库初始化成功！")
    except Exception as e:
        print(f"数据库初始化失败: {e}")
    finally:
        if conn:
            conn.close()

if __name__ == "__main__":
    init_database() 